package com.hunter.sign.server.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.docx4j.model.datastorage.XPathEnhancerParser.main_return;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.hunter.common.base.BaseController;
import com.hunter.common.util.DateUtil;
import com.hunter.common.util.PropertiesFileUtil;
import com.hunter.common.util.StringUtil;
import com.hunter.sign.common.constant.SignResult;
import com.hunter.sign.common.constant.SignResultConstant;
import com.hunter.sign.common.util.ParamProcess;
import com.hunter.sign.server.vo.request.FileUploadReq;
import com.hunter.sign.server.vo.response.FileUploadResp;


/**
 * 文件上传
 * @author hunter
 */
@Controller
@RequestMapping("/file")
public class FileController  extends BaseController {

	private Logger logger = LoggerFactory.getLogger(FileController.class);
	
	/**
	 * 文件上传
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/upload")
	public void upload(HttpServletRequest request, HttpServletResponse response, @RequestParam(value="files")MultipartFile[] files, FileUploadReq fileUploadReq) throws IOException {
		logger.info("文件上传--------------,fileUploadReq:"+fileUploadReq);
		// 参数校验失败
		if (!ParamProcess.paramValid(fileUploadReq, FileUploadReq.class)) {
			outHttpJson(response, new SignResult(SignResultConstant.FAILED, null));
			return;
		}
		List<FileUploadResp> list = new ArrayList<FileUploadResp>();
//		MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//		MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
//		Iterator<String> ite = multipartRequest.getFileNames();
//		logger.info("文件上传--------------,list:"+list.size());
//		while(ite.hasNext()){
//			MultipartFile multipartFile = multipartRequest.getFile(ite.next());
//			if(multipartFile != null){
//	 			if (multipartFile.getSize() > 20*1024 * 1024) {
//	 				outHttpJson(response, new SignResult(SignResultConstant.FAILED, null));
//	 				return;
//				}
//				FileUploadResp fileUploadResp = new FileUploadResp();
//				fileUploadResp.setFileName(multipartFile.getOriginalFilename());
//				String newFileName = StringUtil.getLongName();
//				if(multipartFile.getOriginalFilename().indexOf(".")!=-1){
//					newFileName += multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".")).toLowerCase();
//				}
//				String basepath = DateUtil.getCurrentDate()+File.separator+DateUtil.getCurrentHour();
//				String filePath = PropertiesFileUtil.getInstance("config").get("file.path")+File.separator+basepath;
//				String urlPath = PropertiesFileUtil.getInstance("config").get("file.url")+File.separator+basepath;
//				File file = new File(filePath);
//				if (!file.exists()) {
//					file.mkdirs();
//				}
//				FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), new File(filePath, newFileName));
//				fileUploadResp.setUrl(urlPath+File.separator+newFileName);
//				list.add(fileUploadResp);
//			}
//		}
		logger.info("文件上传--------------,files:"+files.length);
		for(MultipartFile multipartFile:files){
 			if (multipartFile.getSize() > 20*1024 * 1024) {
				outHttpJson(response, new SignResult(SignResultConstant.FAILED, null));
				return;
 			}
			FileUploadResp fileUploadResp = new FileUploadResp();
			fileUploadResp.setFileName(multipartFile.getOriginalFilename());
			String newFileName = StringUtil.getLongName();
			if(multipartFile.getOriginalFilename().indexOf(".")!=-1){
				newFileName += multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".")).toLowerCase();
			}
			String basepath = DateUtil.getCurrentDate()+"/"+DateUtil.getCurrentHour();
			String filePath = PropertiesFileUtil.getInstance("config").get("file.path")+"/"+basepath;
			String urlPath = PropertiesFileUtil.getInstance("config").get("file.url")+"/"+basepath;
			File file = new File(filePath);
			if (!file.exists()) {
				file.mkdirs();
			}
			FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), new File(filePath, newFileName));
//			fileUploadResp.setUrl(urlPath+"/"+newFileName);
			fileUploadResp.setUrl(filePath+"/"+newFileName);
			list.add(fileUploadResp);
		}
		logger.info("文件上传--------------,list:"+list.size());
		outHttpJson(response, new SignResult(SignResultConstant.SUCCESS, list));
	}

	public static void main(String[] args) {
		System.out.println("\\\\".replace("\\", "/"));
	}

}
